import React, { useState, useEffect, useCallback, useImperativeHandle, forwardRef } from 'react';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import PropTypes from 'prop-types';

const RichTextEditor = forwardRef(({ detail }, ref) => {
  const [editorState, setEditorState] = useState(() => {
    if (detail) {
      const blocksFromHtml = htmlToDraft(detail);
      const { contentBlocks, entityMap } = blocksFromHtml;
      const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
      return EditorState.createWithContent(contentState);
    }
    return EditorState.createEmpty();
  });

  useEffect(() => {
    if (detail) {
      const blocksFromHtml = htmlToDraft(detail);
      const { contentBlocks, entityMap } = blocksFromHtml;
      const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
      setEditorState(EditorState.createWithContent(contentState));
    } else {
      setEditorState(EditorState.createEmpty());
    }
  }, [detail]);

  const onEditorStateChange = useCallback((newEditorState) => {
    setEditorState(newEditorState);
  }, []);

  const getDetail = useCallback(() => {
    return draftToHtml(convertToRaw(editorState.getCurrentContent()));
  }, [editorState]);

  useImperativeHandle(ref, () => ({
    getDetail
  }));

  return (
    <Editor
      editorState={editorState}
      editorStyle={{ height: 250, border: '1px solid #000', padding: '0 30px' }}
      onEditorStateChange={onEditorStateChange}
    />
  );
});

RichTextEditor.propTypes = {
  detail: PropTypes.string,
};

export default RichTextEditor;